﻿using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace XinLife.Core.HttpHandler
{
    public class LogHandler : DelegatingHandler
    {
        private readonly ILogger<LogHandler> _logger;//日志
        public LogHandler(ILogger<LogHandler> logger)
        {
            _logger = logger;
        }


        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            //if (!request.Headers.Contains("X-API-KEY"))
            //{
            //    return new HttpResponseMessage(HttpStatusCode.BadRequest)
            //    {
            //        Content = new StringContent(
            //            "The API key header X-API-KEY is required.")
            //    };
            //}
            StringBuilder log = new StringBuilder();
            log.AppendLine($"\r\nRequest:{request.Method}:{request.RequestUri}");
            if (request.Content != null)
            {
                log.AppendLine($"Request Body:{await request.Content.ReadAsStringAsync()}");
            }
            log.AppendLine("Request StartTime：" + DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));

            var fWatch = new Stopwatch();
            fWatch.Start();
            var httpResponseMessage = await base.SendAsync(request, cancellationToken);
            fWatch.Stop();

            log.AppendLine("Response EndTime：" + DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
            log.Append($"Response Body({fWatch.ElapsedMilliseconds}ms):\r\n{await httpResponseMessage.Content.ReadAsStringAsync()}");

            _logger.LogInformation(AppLogEvents.HTTP, log.ToString());
            return httpResponseMessage;
        }
    }
}
